package com.baidu.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.shop.base.BaseApiService;
import com.baidu.shop.base.Result;
import com.baidu.shop.component.MrRabbitMQ;
import com.baidu.shop.constant.MqMessageConstant;
import com.baidu.shop.dto.SkuDTO;
import com.baidu.shop.dto.SpuDTO;
import com.baidu.shop.dto.SpuDetailDTO;
import com.baidu.shop.entity.*;
import com.baidu.shop.feign.SearchFeign;
import com.baidu.shop.feign.TemplateFeign;
import com.baidu.shop.mapper.*;
import com.baidu.shop.service.GoodsService;
import com.baidu.shop.utils.BaiduBeanUtil;
import com.baidu.shop.utils.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: GoodsServiceImpl
 * @Author: User
 * @date: 2020.09.07 14:12
 * @version: 1.0
 */
@RestController
public class GoodsServiceImpl extends BaseApiService implements GoodsService {
    @Resource
    private SpuMapper mapper;

    @Resource
    private SpuDetailMapper spuDetailMapper;

    @Resource
    private SkuMapper skuMapper;

    @Resource
    private StockMapper stockMapper;

    @Resource
    private TemplateFeign templateFeign;

    @Resource
    private SearchFeign searchFeign;

    @Autowired
    private MrRabbitMQ mrRabbitMQ;

    @Override
    public Result<SkuEntity> getSkuBySkuId(Long skuId) {
        SkuEntity skuEntity = skuMapper.selectByPrimaryKey(skuId);
        return this.setResultSuccess(skuEntity);
    }

    @Override
    @Transactional
    public Result<JSONObject> editGoodaleable(SpuDTO spuDTO) {
        SpuEntity spuEntity = new SpuEntity();
        spuEntity.setId(spuDTO.getId());
        if (spuDTO.getSaleable()==1){
            spuEntity.setSaleable(0);
        }else{
            spuEntity.setSaleable(1);
        }
        mapper.updateByPrimaryKeySelective(spuEntity);
        return this.setResultSuccess();
    }

    @Override
    @Transactional
    public Result<JSONObject> deleteGoods(Integer spuId) {
        //删除spu
        mapper.deleteByPrimaryKey(spuId);
        //删除spuDetail
        spuDetailMapper.deleteByPrimaryKey(spuId);
        //根据spuid获取skuids
        List<Long> skuIds = getSkuIdsBySpuId(spuId);
        //根据skuids 删除sku 和 stock
        //判断skuids长度是否为空 避免删除所有数据
        if (!skuIds.isEmpty()){
            //删除sku
            skuMapper.deleteByIdList(skuIds);
            //删除stock
            stockMapper.deleteByIdList(skuIds);
        }
        //事务提交成功后操作
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                /*searchFeign.deleteSearchById(spuId.toString());
                File file = new File("E:\\static-html\\item\\"+spuId+".html");
                if (file.exists()) {
                    file.delete();
                }*/
                mrRabbitMQ.send(spuId.toString(), MqMessageConstant.SPU_ROUT_KEY_DELETE);
            }
        });
        return this.setResultSuccess();
    }

    @Override
    @Transactional
    public Result<JSONObject> editGoods(SpuDTO spuDTO) {

        System.out.println(spuDTO);

        //修改spu
        SpuEntity spuEntity = BaiduBeanUtil.copyProperties(spuDTO, SpuEntity.class);
        Date date = new Date();
        spuEntity.setLastUpdateTime(date);
        mapper.updateByPrimaryKeySelective(spuEntity);

        //修改spudetail
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        SpuDetailEntity spuDetailEntity = BaiduBeanUtil.copyProperties(spuDetail, SpuDetailEntity.class);
        spuDetailMapper.updateByPrimaryKeySelective(spuDetailEntity);

        //修改sku 要先删除原先的sku
        //根据spu id 获取所有的sku 遍历sku 获取sku id 的集合，根据sku id 集合删除sku数据
        //获取skuids的代码提取出来了
        List<Long> skuIds = getSkuIdsBySpuId(spuDTO.getId());
        //判断是否有skuIds,避免全表删除
        if (!skuIds.isEmpty()){
            skuMapper.deleteByIdList(skuIds);

            //修改stock 要先删除原先的stock
            //stock 的主键就是 sku id 上面已经遍历出sku id 了
            stockMapper.deleteByIdList(skuIds);
        }
        //新增sku 和 stock
        List<SkuDTO> skus = spuDTO.getSkus();

        //多余的代码提取出来了
        saveSkusAndStocks(skus, date, spuDTO.getId());

        //事务提交后执行
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
               /* Result<JSONObject> initGoodsResult = searchFeign.initGoodsEsData(spuDTO.getId());
                if (initGoodsResult.getCode()==200){
                    System.out.println("文档创建成功");
                }
                Result<JSONObject> staticHTMLTemplate = templateFeign.createStaticHTMLTemplate(spuDTO.getId());
                if (staticHTMLTemplate.getCode()==200){
                    System.out.println("模板创建成功");
                }*/
                mrRabbitMQ.send(spuDTO.getId().toString(), MqMessageConstant.SPU_ROUT_KEY_UPDATE);
            }
        });

        return this.setResultSuccess();
    }

    private List<Long> getSkuIdsBySpuId(Integer spuId){
        Example example = new Example(SkuEntity.class);
        example.createCriteria().andEqualTo("spuId",spuId);
        List<SkuEntity> skuEntities = skuMapper.selectByExample(example);
        List<Long> skuIds = skuEntities.stream().map(skuEntity -> skuEntity.getId()).collect(Collectors.toList());
        return skuIds;
    }
    private void saveSkusAndStocks(List<SkuDTO> skus, Date date,Integer spuId){
        skus.stream().forEach(skuDTO -> {
            SkuEntity skuEntity = BaiduBeanUtil.copyProperties(skuDTO, SkuEntity.class);
            skuEntity.setSpuId(spuId);
            skuEntity.setCreateTime(date);
            skuEntity.setLastUpdateTime(date);
            skuMapper.insertSelective(skuEntity);
            //新增stock库存
            StockEntity stockEntity = new StockEntity();
            stockEntity.setSkuId(skuEntity.getId());
            stockEntity.setStock(skuDTO.getStock());
            stockMapper.insertSelective(stockEntity);
        });
    }
    @Override
    @Transactional
    public Result<SpuDetailEntity> getSpuDetailBydSpu(Integer spuId) {
        SpuDetailEntity spuDetailEntity = spuDetailMapper.selectByPrimaryKey(spuId);
        return this.setResultSuccess(spuDetailEntity);
    }

    @Override
    public Result<List<SkuDTO>> getSkuBySpuId(Integer spuId) {
        List<SkuDTO> skuDTO = skuMapper.selectSkuAndStockBySpuId(spuId);
        return this.setResultSuccess(skuDTO);
    }

    @Override
    @Transactional
    public Result<JSONObject> saveGoods(SpuDTO spuDTO){

        //新增spu
        SpuEntity spuEntity = BaiduBeanUtil.copyProperties(spuDTO, SpuEntity.class);
        Date date = new Date();
        spuEntity.setSaleable(1);//是否上架
        spuEntity.setValid(1);//是否生效
        spuEntity.setCreateTime(date);
        spuEntity.setLastUpdateTime(date);
        mapper.insertSelective(spuEntity);
        Integer spuId = spuEntity.getId();
        //新增spuDetail
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        SpuDetailEntity spuDetailEntity = BaiduBeanUtil.copyProperties(spuDetail, SpuDetailEntity.class);
        spuDetailEntity.setSpuId(spuId);
        spuDetailMapper.insertSelective(spuDetailEntity);
        //新增sku
        List<SkuDTO> skus = spuDTO.getSkus();
        //多余的代码提取出来了
        saveSkusAndStocks(skus, date, spuId);

        //事务提交后执行
       TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
           @Override
           public void afterCommit() {
              /* Result<JSONObject> initGoodsResult = searchFeign.initGoodsEsData(spuId);
               if (initGoodsResult.getCode()==200){
                   System.out.println("文档创建成功");
               }
               Result<JSONObject> staticHTMLTemplate = templateFeign.createStaticHTMLTemplate(spuId);
               if (staticHTMLTemplate.getCode()==200){
                   System.out.println("模板创建成功");
               }*/
               mrRabbitMQ.send(spuId.toString(), MqMessageConstant.SPU_ROUT_KEY_SAVE);
           }
       });
        return  this.setResultSuccess();
    }

    @Override
    public Result<PageInfo<SpuDTO>> getSpuInfo(SpuDTO spuDTO) {
        //分頁查询
        if (ObjectUtil.isNotNull(spuDTO.getPage())
                && ObjectUtil.isNotNull(spuDTO.getPagesize()))
            PageHelper.startPage(spuDTO.getPage(), spuDTO.getPagesize());
        //Integer total= mapper.getTotal(spuDTO);
        // spuDTO.setPage((spuDTO.getPage()-1)*spuDTO.getPagesize());
        //查询
        List<SpuDTO> spu = mapper.getSpu(spuDTO);
/*
        //实例化条件对象
        Example example = new Example(SpuEntity.class);
        Example.Criteria criteria = example.createCriteria();
        //排序
        if(StringUtil.isNotEmpty(spuDTO.getSort()))
            example.setOrderByClause(spuDTO.getOrderByClause());
        //是否上架
        if(ObjectUtil.isNotNull(spuDTO.getSaleable())&& spuDTO.getSaleable() != 2)
            criteria.andEqualTo("saleable",spuDTO.getSaleable());
        //条件查询
        if (StringUtil.isNotEmpty(spuDTO.getTitle()))
            criteria.andLike("title", "%"+spuDTO.getTitle()+"%");
        //执行查询
        List<SpuEntity> spuEntities = mapper.selectByExample(example);


        //遍历返回查询品牌名,和类型
        List<SpuDTO> collect = spuEntities.stream().map(spuEntity -> {

           //根据品牌id 查询品牌
            BrandEntity brandEntity = bmapper.selectByPrimaryKey(spuEntity.getBrandId());
           //根据cid1,cid2,cid3 in()多查询类型
            List<CategoryEntity> categoryEntities = categoryMapper.selectByIdList(Arrays.asList(spuEntity.getCid1(), spuEntity.getCid2(), spuEntity.getCid3()));
            //遍历类型 根据‘/’分割 类型名 返回字符串
            String categoryName = categoryEntities.stream().map(category -> {
                return category.getName();
            }).collect(Collectors.joining("/"));
            //beanCopy 将值赋予给spudto
            SpuDTO spuDTO1 = BaiduBeanUtil.copyProperties(spuEntity, SpuDTO.class);
            spuDTO1.setBrandName(brandEntity.getName());
            spuDTO1.setCategoryName(categoryName);
            SpuDTO infoById = mapper.getInfoById(spuEntity.getId());
            return infoById;
        }).collect(Collectors.toList());

        //获取分页数据
        PageInfo<SpuEntity> PageInfo = new PageInfo<>(spuEntities);
        //获取总条数
        long total = PageInfo.getTotal();*/
        //获取分页数据
        return this.setResultSuccess(new PageInfo<>(spu));
    }
}
